<?php

namespace app\home\service;

use app\home\model\Order;
use app\home\model\UserPropsInfo;
use think\Db;
use app\home\model\Player;

class GameProcessMonthCard extends GameBase
{

    public function orderProcess()
    {

        $this->order_select = (new Order())->checkOrderNew($this->order_id, $this->total_price);
        // if($this->order_select == false){
        //     return false;
        // }

        if(isset($this->order_select['code']) && ($this->order_select['code'] == -1 || $this->order_select['code'] == -2)){
            // 订单异常
            mylog($this->order_select['msg']);
            return false;
        }

        if($this->order_select['status'] == 1){
            // 重复订单直接一般需要直接返回成功
            // 在重复订单的基础上判断是否是续订订单 如果不是 直接返回true

            $res= $this->checkMonthCardOrder();

            mylog($res);
            if($res['code'] == 1){
                // 满足续订 用新生成的订单号替换原来的订单号
                $this->order_id = $res['new_order_id'];
            }else if($res['code'] == -1){
                // 满足续订 但续订次数异常
                return true;
            }else{
                return true;
            }
        }

        $billing_id = $this->order_select['goods_id'];
        $UserID = $this->order_select['userid'];
        $this->player_select = (new Player())->field($this->player_field)->where('UserID', $UserID)->find()->toArray();

        // 防止出现计费点找不到的情况
        $billing_point_array = $this->getBillingPoint($billing_id);
        if (empty($billing_point_array)) {
            mylog('billing_point not found');
            return false;
        }

        // 只允许计费点类型1000
        if ($billing_point_array['Type'] != 1000) {
            mylog($billing_id . ' not found');
            return false;
        }

        // 计费点的价格配置可能有异常
        if (!isset($billing_point_array['Price']) || !is_numeric($billing_point_array['Price'])) {
            mylog($billing_id . ' Price invalid');
            return false;
        }

        // 特殊处理比例不是1比10的情况
        if(isset($billing_point_array['SMoney'])){
            $SMoney = $billing_point_array['SMoney'];
        }else{
            $SMoney = $billing_point_array['Price'] * 10;
        }

        array_push($this->props_array, [3, $SMoney, 0]);

        /*充值赢大礼*/
        $this->Recharge_wins_big_gifts($UserID, $billing_point_array['Price'], $billing_id);

        /*充值道具活动*/
        $item_arr = $this->Recharge_item_recharge_activity($UserID, $billing_point_array['Price']);
        if (!empty($item_arr)) {
            $this->props_array = array_merge($this->props_array, $item_arr);
        }
        /*处理Vip等级*/
        $this->processVipLevel();

        // 开启事务
        try {
            $db = Db::connect('db_config2');
            $db->startTrans();
        } catch (\Exception $e) {
            mylog($e->getMessage());
            return false;
        }

        try {

            $time = date('Y-m-d H:i:s');

            $data['status'] = 1;
            $data['paydate'] = $time;
            $data['transactionID'] = $this->extra['trade_no'];

            if ((new Order())->save($data, ['id' => $this->order_id]) == false) {
                throw new \Exception('Order rollback');
            }

            $this->player_update['ChargeScore'] = $this->player_select['ChargeScore'] + $billing_point_array['Price'];
            $this->player_update['TotalRecharge'] = $this->player_select['TotalRecharge'] + $billing_point_array['Price'];
            $this->player_update['RechargeTimes'] = $this->player_select['RechargeTimes'] + 1;
            $this->player_update['SMoney'] = $this->player_select['SMoney'] + $SMoney;

            if ((new Player())->save($this->player_update, ['UserID' => $UserID]) == false) {
                throw new \Exception('Order rollback');
            }

            $db->commit();

            /*向游戏服务器发送充值消息*/
            if ($this->get_curl_type($UserID,$this->props_array) == false) {
                mylog('通知服务器失败');
            }

            $this->Recharge_score_log();
            mylog('订单处理ok');

            // 把充值总额写入到有序集合
            $redis = new \Redis();
            $redis->connect(config('REDIS_FORMAL.host'), config('REDIS_FORMAL.port'));
            $redis->auth(config('REDIS_FORMAL.auth'));
            $redis->select(0);
            $time = date("Ymd");
            $redis->zIncrBy('recharge_' . $time, $billing_point_array['Price'], $UserID);

            return true;
        } catch (\Exception $e) {
            mylog($e->getMessage());
            $db->rollback();
            return false;
        }
    }

    /**
     * 校验月卡自动续费订单类型
     * @param $order_id
     * @param $total_price
     * @param $transactionID
     * @return array|false
     */
    public function checkMonthCardOrder()
    {
        $order = new Order();
        try {
            // 检查计费点
            $row = $order->where('id',$this->order_id)->field('goods_id,userid')->find();
            $goods_id = $row['goods_id'];
            $userid = $row['userid'];
            if(in_array($goods_id,[UserPropsInfo::IOS_WEEK_CARD_ID,UserPropsInfo::IOS_MONTH_CARD_ID])){
                // 如果我方订单已经成功处理 且 对方订单是新的订单号 就认为满足续订逻辑
                if($order::get(['transactionID'=>$this->extra['trade_no']]) == false){

                    // 满足续订逻辑情况下 判断续订次数
                    // 续订月卡,判断最近30天月卡续订次数 大于2次 则不发奖励
                    // 续订周卡,判断最近7天周卡续订次数 大于2次 则不发奖励
                    // 周卡
                    if($goods_id == UserPropsInfo::IOS_WEEK_CARD_ID){
                        $where1 = date('Y-m-d H:i:s',strtotime('-7 day'));
                    }else{
                        // 月卡
                        $where1 = date('Y-m-d H:i:s',strtotime('-30 day'));
                    }

                    $count = $order
                        ->where('userid',$userid)
                        ->where('goods_id',$goods_id)
                        ->where('status',1)
                        ->where('paydate','>=',$where1)->count();
                    if($count > 2){
                        return ['code'=>-1,'msg'=>'续订次数异常'];
                    }

                    $data = [
                        'id' => get_microtimes(),
                        'userid' => $this->order_select['userid'],
                        'goods_id' => $this->order_select['goods_id'],
                        'amount' => $this->order_select['amount'],
                        'status' => 0,
                        'channel_id' => $this->order_select['channel_id'],
                        'SpreaderID' => $this->order_select['SpreaderID'],
                        'tradetype' => 4,
                        'extra' => '',
                        'comment' => '续订:'.$this->order_select['id'],
                        'createdat' => date('Y-m-d H:i:s', time()),
                        'registerat' => $this->order_select['registerat']
                    ];
                    if($order_model = $order::create($data)){
                        return ['code'=>1,'new_order_id'=>$order_model->id];
                    }
                }
            }

            return ['code'=>0];
        } catch (\Exception $e) {
            mylog($e->getMessage());
            return ['code'=>0,'msg'=>'订单异常:'.$e->getMessage()];
        }
    }

}
